import neopixel
from machine import Pin
import time

"""
WS2812 WS2812B 灯带
"""

class WS2812:
    def __init__(self, pin, n = 8):
        self.__brightness = 100
        self.__pin = Pin(pin, Pin.OUT)
        self.__np = neopixel.NeoPixel(self.__pin, n)

    def setBrightness(self, brightness):
        self.__brightness = brightness

    def fill(self, color):
        n = self.__np.n
        v = (int(color[0] * self.__brightness / 100), int(color[1] * self.__brightness / 100), int(color[2] * self.__brightness / 100))
        for i in range(n):
            self.__np[i] = v
        self.__np.write()

    def fade_in_out(self, count = 1):
        n = self.__np.n
        for i in range(0, count * 2 * 256, 8):
            for j in range(n):
                if (i // 256) % 2 == 0:
                    val = i & 0xFF
                else:
                    val = 255 - (i & 0xFF)
                self.__np[j] = (val, val, val)
            self.__np.write()

    def cycle(self):
        n = self.__np.n
        for i in range(4 * n):
            for j in range(n):
                self.__np[j] = (0, 0, 0)
            self.__np[i % n] = (255, 255, 255)
            self.__np.write()
            time.sleep_ms(25)

    def bounce(self):
        n = self.__np.n
        for i in range(4 * n):
            for j in range(n):
                self.__np[j] = (0, 0, 128)
            if (i // n) % 2 == 0:
                self.__np[i % n] = (0, 0, 0)
            else:
                self.__np[n - 1 - (i % n)] = (0, 0, 0)
            self.__np.write()
            time.sleep_ms(60)

    def rainbow(self):
        pass

    def clear(self):
        for i in range(self.__np.n):
            self.__np[i] = (0, 0, 0)
        self.__np.write()



